//
//  FQDColumnUsersView.m
//  FakeQDaily
//
//  Created by mewxiv on 9/23/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDColumnUsersView.h"
#import "FQDRestModel.h"

#import "UIImageView+WebCache.h"

static CGFloat const kItemSpanX = 46.6f;
static CGFloat const kItemSpanY = 47.0f;
static CGFloat const kItemSize = 37.0f;
static CGFloat const kCircleItemSize = 45.0f;
static NSInteger const kItemCountPerRow = 6;

@interface FQDColumnUsersView ()

@property (nonatomic, strong) NSArray *userImageViews;
@property (nonatomic, strong) UIImageView *circleImageView;

@end

@implementation FQDColumnUsersView

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self updateUserSubviews];
    [self updateCircleImageView];
}

- (CGSize)intrinsicContentSize
{
    NSInteger rowCount = ceil([self.users count] / (CGFloat)kItemCountPerRow);
    return CGSizeMake(UIViewNoIntrinsicMetric, rowCount * kItemSpanY);
}

- (void)updateUserSubviews
{
    NSInteger remainItemCount = [self.users count];
    NSInteger imageViewIndex = 0;
    CGFloat x = 0;
    CGFloat y = 0;
    
    while (remainItemCount > kItemCountPerRow) {
        for (NSInteger i = 0; i < kItemCountPerRow; i++) {
            CGRect avatarFrame = CGRectMake(x, y, kItemSize, kItemSize);
            UIImageView *avatarImageView = self.userImageViews[imageViewIndex];
            avatarImageView.frame = avatarFrame;
            
            imageViewIndex++;
            x += kItemSpanX;
        }
        remainItemCount -= kItemCountPerRow;
        x = 0;
        y += kItemSpanY;
    }
    
    CGFloat viewWidth = self.bounds.size.width;
    CGFloat lastRowItemsWidth = ((remainItemCount - 1) * kItemSpanX)+kItemSize;
    x = (viewWidth - lastRowItemsWidth) / 2;
    for (NSInteger i = 0; i < remainItemCount; i++) {
        CGRect avatarFrame = CGRectMake(x, y, kItemSize, kItemSize);
        UIImageView *avatarImageView = self.userImageViews[imageViewIndex];
        avatarImageView.frame = avatarFrame;
        
        imageViewIndex++;
        x += kItemSpanX;
    }
}

- (void)updateCircleImageView
{
    __block NSInteger selectedIdx = NSNotFound;
    [self.users enumerateObjectsUsingBlock:^(FQDAuthor *author, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([author.ID isEqualToString:self.selectedUserId]) {
            selectedIdx = idx;
            *stop = YES;
        }
    }];
    
    if (selectedIdx != NSNotFound) {
        UIImageView *userImageView = self.userImageViews[selectedIdx];
        self.circleImageView.center = userImageView.center;
        self.circleImageView.hidden = NO;
        [self bringSubviewToFront:self.circleImageView];
    } else {
        self.circleImageView.hidden = YES;
    }
}

- (UIImageView *)createAvatarImageViewWithUserIndex:(NSInteger)userIndex
{
    FQDAuthor *author = (FQDAuthor *)self.users[userIndex];
    NSURL *avatarURL = [NSURL URLWithString:author.avatar];
    UIImage *defaultImage = [UIImage imageNamed:@"avatar_default_icon_normal"];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.layer.cornerRadius = kItemSize / 2;
    [imageView sd_setImageWithURL:avatarURL placeholderImage:defaultImage];
    return imageView;
}

- (void)setUsers:(NSArray *)users
{
    _users = users;
    
    for (UIView *imageView in self.userImageViews) {
        [imageView removeFromSuperview];
    }
    
    NSMutableArray *imageViews = [NSMutableArray array];
    for (NSInteger i = 0; i < [users count]; i++) {
        UIImageView *avatarImageView = [self createAvatarImageViewWithUserIndex:i];
        [self addSubview:avatarImageView];
        [imageViews addObject:avatarImageView];
    }
    self.userImageViews = [imageViews copy];
    
    self.circleImageView.hidden = YES;
    [self invalidateIntrinsicContentSize];
    [self setNeedsLayout];
}

- (void)setSelectedUserId:(NSString *)selectedUserId
{
    _selectedUserId = selectedUserId;
    
    [self updateCircleImageView];
}

- (UIImageView *)circleImageView
{
    if (!_circleImageView) {
        CGRect circleFrame = CGRectMake(0, 0, kCircleItemSize, kCircleItemSize);
        UIImage *circleImage = [UIImage imageNamed:@"cycle"];
        _circleImageView = [[UIImageView alloc] initWithFrame:circleFrame];
        _circleImageView.image = circleImage;
        [self addSubview:_circleImageView];
    }
    return _circleImageView;
}

@end
